package com.hotel.payment.controller;

import com.hotel.common.utils.DBTools;
import com.hotel.common.utils.Result;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
/**
 * 测试类，Proxy都是
 */
@RestController
@RequestMapping({"/order/orders", "/api/order/orders"})
public class OrderProxyController {

    @GetMapping
    public Result<List<Map<String, String>>> list(@RequestParam(name = "userId", required = false) Long userId) {
        String base = "SELECT id, user_id AS userId, hotel_id AS hotelId, room_id AS roomId, status, checkin_date AS checkinDate, checkout_date AS checkoutDate, amount, created_at AS createdAt FROM orders";
        List<Map<String, String>> data = userId == null
                ? DBTools.query(base + " ORDER BY id DESC")
                : DBTools.query(base + " WHERE user_id=? ORDER BY id DESC", userId);
        return Result.success(data);
    }

    @PostMapping
    public synchronized Result<Long> createAndPay(@RequestBody Map<String, Object> body) {
        try {
            Long userId = body.get("userId") == null ? null : Long.parseLong(body.get("userId").toString());
            Long hotelId = Long.parseLong(body.get("hotelId").toString());
            Long roomId = Long.parseLong(body.get("roomId").toString());
            String checkinDate = (String) body.get("checkinDate");
            String checkoutDate = (String) body.get("checkoutDate");

            // 按订单服务相同规则计算单晚金额：命中季节价则用季节价，否则基础价
            String season = DBTools.querySingle("SELECT price FROM room_price_season WHERE room_id=" + roomId + " AND '" + checkinDate + "' BETWEEN start_date AND end_date ORDER BY id DESC LIMIT 1");
            Double amount;
            if (season != null && season.length() > 0) {
                amount = Double.parseDouble(season);
            } else {
                String base = DBTools.querySingle("SELECT price FROM room WHERE id=" + roomId);
                amount = Double.parseDouble(base);
            }

            // 扣减库存
            int affected = DBTools.update("UPDATE room SET inventory = inventory - 1 WHERE id=? AND inventory > 0", roomId);
            if (affected == 0) {
                return Result.fail("房间库存不足");
            }

            // 创建订单（状态直接标记为 PAID 以放行）
            String insertOrderSql = "INSERT INTO orders(user_id,hotel_id,room_id,status,checkin_date,checkout_date,amount) VALUES(?,?,?,?,?,?,?)";
            DBTools.update(insertOrderSql, userId, hotelId, roomId, "PAID", checkinDate, checkoutDate, amount);
            String id = DBTools.querySingle("SELECT LAST_INSERT_ID() AS id");
            Long orderId = Long.valueOf(id);

            // 写入支付记录（成功）
            String paymentMethod = (String) body.getOrDefault("paymentMethod", "alipay");
            String payChannel = "ALIPAY";
            if ("wechat".equalsIgnoreCase(paymentMethod)) {
                payChannel = "WECHAT";
            }
            Double payAmount = null;
            try {
                payAmount = body.get("amount") == null ? null : Double.parseDouble(body.get("amount").toString());
            } catch (Exception ignored) {}
            if (payAmount == null) {
                payAmount = amount;
            }
            String insertPaymentSql = "INSERT INTO payment(order_id,pay_channel,pay_status,amount) VALUES(?,?,?,?)";
            DBTools.update(insertPaymentSql, orderId, payChannel, "SUCCESS", payAmount);

            return Result.success(orderId);
        } catch (Exception e) {
            return Result.fail("下单支付失败: " + e.getMessage());
        }
    }
}


